<template>
  <div class="user-managee">
    <div class="query-from"  v-has="'role-query'">
    <QueryForm :form="queryForm" v-model="pager" @handleQuery="handleQuery" @reset="reset"/>
       <!-- <el-form :inline="true" class="demo-form-inline" ref="searchForm" :model="pager">
   <el-form-item label="用户id"  label-width="100px" prop="userName" >
      <el-input v-model="pager.userId" autocomplete="false" />
    </el-form-item>
     <el-form-item label="用户名"  label-width="100px" prop="userEmail" >
      <el-input v-model="pager.userName" autocomplete="false" />
    </el-form-item>
    <el-form-item label="用户状态"  label-width="100px" prop="state">
      <el-select v-model="pager.state" placeholder="请选择状态">
        <el-option label="在职" :value="1" />
        <el-option label="离职" :value="2" />
        <el-option label="试用期" :value="3 "/>
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="searchUser" >查询</el-button>
       <el-button  @click="reset()">重置</el-button>
    </el-form-item>
  </el-form> -->
    </div>
    <div class="base-table">
      <div class="action">
        <el-button type="primary" @click="addUser" v-has="'user-create'">新增</el-button>
        <el-button type="danger" @click="deleteSelect" v-has="'user-patch-delete'" >删除选中</el-button>
      </div>
      <el-table
       v-loading="loading"
      :data="userList"
        style="width: 100%;"
       @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"  />
        <el-table-column v-for="item in columns"
        :key="item.prop"
        :prop="item.prop"
        :label="item.label"
        :formatter="item.formatter"
        >
          
        </el-table-column>
      <el-table-column label="操作">
          <template #default="scope" in-width="100">
            <el-button type="primary" @click="edit(scope.row)" v-has="'user-edit'">编辑</el-button>
            <el-button type="danger"  :disabled="scope.row.state==2"  @click="deleteItem(scope.row)" v-has="'user-delete'">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
 <div class="example-pagination-block">
     
    <el-pagination background layout="prev, pager, next" :total="total" @current-change="getpages" :page-size="pager.pageSize"/>
  </div>
        <el-dialog
    v-model="dialogVisible" :title="action=='add'?'新建用户':'修改用户'" 
    @close="handleCancel"
    >
      <el-form :model="form"  ref="dialogForm" :rules="rule">
    <el-form-item label="用户名"  label-width="100px" prop="userName" >
      <el-input v-model="form.userName" autocomplete="false" :disabled="action=='add'?false:true"/>
    </el-form-item>
    <el-form-item label="邮箱"  label-width="100px" prop="userEmail">
      <el-input v-model="form.userEmail" autocomplete="false" :disabled="action=='add'?false:true"/>
    </el-form-item>
       <el-form-item label="号码"  label-width="100px" prop="userPhone">
      <el-input v-model="form.mobile" autocomplete="false"/>
    </el-form-item>
       <el-form-item label="岗位"  label-width="100px" prop="job">
      <el-input v-model="form.job" autocomplete="false"/>
    </el-form-item>
    <el-form-item label="用户状态"  prop="state" label-width="100px">
      <el-select v-model="form.state" >
        <el-option label="在职" :value="1" />
        <el-option label="离职" :value="2" />
        <el-option label="试用期" :value="3" />
      </el-select>
    </el-form-item>
     <el-form-item label="系统角色"  label-width="100px">
      <el-select v-model="form.roleList" multiple  placeholder="选择用户角色" style="width:100%">
        <el-option  v-for="item in roleList" 
        :key="item._id"
        :label="item.roleName"
         :value="item._id"
        />
      </el-select>
    </el-form-item>
   
    <el-form-item  label="部门"  label-width="100px">
       <div class="example-block">
                <el-cascader 
                
                :options="deptList"
                :props="{checkStrictly:true,value:'_id',label:'deptName'}" 
                clearable 
                style="with:100%"  
                placeholder="请选择部门" 
                 v-model="form.deptId"
                 
                />
                </div>
            </el-form-item>

    <!-- <el-form-item>
    
    </el-form-item> --> 
    </el-form>
    <template #footer>
<span>
  <el-button type="primary" @click="handleSubmit(dialogForm)">{{action=='add'?'新建':"修改"}}</el-button>
      <el-button @click="dialogVisible=!dialogVisible">取消</el-button>
</span>

    </template>
 
  </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, nextTick,toRaw } from "vue";
import { ElMessage, formatter } from "element-plus";
import  utils  from "../utils/index.js";
import api from "../api/index.js";
import QueryForm from "../packages/QuerForm/QueryForm.vue";


const queryForm=reactive([
{   
    type:"input",
    label:'用户id',
    prop:"userId",
    placeholder:"请输入用户id"
},
{   type:"input",   
    label:'用户名称',
    prop:"userName",
    placeholder:"请输入用户名称"
},
{   type:'select',   
    label:'状态',
    prop:"state",
    placeholder:"请选择用户状态",
    options:[
        {
            value:0,
            label:'所有'
        },
        {
            value:1,
            label:'在职'
        },
        {
            value:2,
            label:'离职'
        },
       {
            value:3,
            label:'试用期'
        },
       
    ]
},

])

//定义校验规则
const rule=reactive({
  userName:{
    required:true,
    message:'请输入用户名',
    trigger:'blur'
  },
   userEmail:{
    required:true,
    message:'请输入邮箱',
    trigger:'blur'
  },
  userPhone:[
    {
      pattern:/1[3-9]\d{9}/,
      message:'请输入正确的手机号码',
      trigger:'blur'
    }
  ]
})
const action=ref('')
const loading=ref(true)
const dialogForm=ref(null)
const searchForm=ref(null)
const user = reactive({
  state: 0,
});

const dialogVisible=ref(false)
const pager = reactive({
  pageNum: 1,
  pageSize: 10,
});
const select=ref([])
const userList=ref([])
const deptList=ref([])
const roleList=ref([])
const total=ref('')
//定义新增模块用户
const form=ref({
  state:0
})

//根据当前页数请求数据
const getpages=(page)=>{
 pager.pageNum=page
  getData(pager)
}
//重置搜索表单
const reset=()=>{
  console.log(searchForm.value);
   
    delete pager.state
    delete pager.userId
     delete pager.userName
   console.log(pager);
   getData(pager)

}
//删除特定项
const deleteItem=(row)=>{
   console.log(row);
//    let data={
//     userIds:[row.userId]
//     }

// deleteData(data)
}


//发送删除请求
const deleteData=async(data)=>{
  
   let result
    try {
    result = await api.delteSelect(data);
  } catch (error) {
    console.log(error.data);
     ElMessage.success("删除失败，请稍后再试");
  }

  if (result.data.code == 200) {
    getUserList()
 
    ElMessage.success("删除成功");
   
  }
}

//监听选中的项目
const handleSelectionChange = (val) => {
  select.value=val

}
// 删除选中
const deleteSelect=()=>{
  let data={
    userIds:[]
    }
    
    
  let index=select.value.map((ele)=>ele.state)
 console.log(index.indexOf(2));
 if(index.indexOf(2)==-1){
  select.value.forEach((ele)=>{
     data.userIds.push(ele.userId)
   })
  deleteData(data)
 }else{
    ElMessage.error('离职人员不可删除')
 }
}
//动态定义表达格式
const columns=reactive([
  {
    label:'用户id',
    prop:"userId"
  },
   {
    label:'用户名',
    prop:"userName"
  },
   {
    label:'用户邮箱',
    prop:"userEmail"
  },
   {
    label:'用户角色',
    prop:"role",
    formatter(row,column,value){
      return{
        0:"管理员",
        1:"普通用户"
      }[value]
    }
  },
   {
    label:'用户状态',
    prop:"state",
    formatter(row,column,value){
      return{
        1:"在职",
        2:"离职",
        3:"试用期"
      }[value]
    }
  },
  {
    label:'注册时间',
    prop:"createTime",
    formatter:(row,column,value)=>{
     return utils.formateDate(new Date(value))
    }
  },
  {
    label:'最后登录时间',
    prop:"lastLoginTime",
     formatter:(row,column,value)=>{
      
     return utils.formateDate(new Date(value))
    }
  },

])
//获取角色列表
const getRoleList=async()=>{
  let result = await api.getRoleNameList();
   roleList.value=result.data.data.list
  
}

//获取部门列表
const getDeptList=async()=>{
  
  let result = await api.getDeptList();


   deptList.value=result.data.data


}
//请求用户数据
const getUserList = async () => {
  let result;
  let params = { ...user, ...pager };
 getData(params)
};

//搜索用户数据
const searchUser=()=>{
   
  let params ={...pager };
    console.log(params);
   getData(params)
}
//通用请求用户列表方法
const getData=async(params)=>{
  loading.value=true
  let result;
  try {
    result = await api.getUserList(params);
  } catch (error) {
    console.log(error.data);
    let message = "";
    if (!error.data) {
      message = "请求失败";
    }
    if (error.data.code == 40001) {
      message = error.data.msg;
    }
    let timer = setTimeout(() => {
      loading.value=true
      ElMessage.error(message);
    }, 3000);
  }

  if (result.data.code == 200) {
     loading.value=false
    userList.value=result.data.data.list
    total.value=result.data.data.page.total
   
  }
}
//定义用户提交事件
const handleSubmit=(dialogForm)=>{
dialogForm.validate((valid) => {
    if (valid) {
      let data =toRaw(form.value)
      sendUserData(data)
    }
  });
}
//重置表单
const handleCancel=()=>{

   dialogForm.value.resetFields()
form.value={
   state:0
}
}
const sendUserData=async(data)=>{

 data.action=action.value
 let result
    try {
    result = await api.operate(data);
  } catch (error) {
    console.log(error.data);
    ElMessage.error(error.data.msg);
  }

  if (result.data.code == 200) {
    getUserList()
   dialogVisible.value=!dialogVisible.value
  
    ElMessage.success("修改成功");
   
  }
}
const addUser=()=>{
  action.value="add"
  dialogVisible.value=!dialogVisible.value
  
}


const edit=(row)=>{
      action.value="edit"
    dialogVisible.value=!dialogVisible.value
    nextTick(()=>{
      Object.assign(form.value,row)
    })
    
}
const handleQuery=(val)=>{
      searchUser()
      console.log(pager);
}
getUserList()
getRoleList()
getDeptList()
</script>

<style lang="scss" scoped>
.query-from{
  width: 100%;
  background-color: white;
  .demo-form-inline{
    display: flex;
    align-items: center;
    justify-content: space-around;
    height: 60px;
    .el-form-item{
      margin: 0;
    }
  }
}
.base-table{
  overflow: hidden;
  .action{
  margin: 20px 20px;
}
}

.user-managee{
  overflow: hidden;
}
.example-pagination-block{
  display: flex;
  justify-content: center;
  margin-top: 25px;
}
</style>
